from django.contrib.auth.models import Permission, ContentType, Group
from django.shortcuts import render

# Create your views here.
from fdfs_client.client import Fdfs_client
from rest_framework.decorators import action
from rest_framework.generics import ListAPIView, CreateAPIView, ListCreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.request import Request
from rest_framework.permissions import IsAdminUser
from datetime import date, timedelta

from rest_framework.viewsets import ModelViewSet

from apps.meiduo_admin.serializer import UserSerializer, SPUSpecificationSerializer, SPUSerializer, SKUImageSerializer, \
    SKUSerializer, SPUSpecificationSerializer2, GoodsCategorySerializer, OrderInfoSerializer, PermissionSerializer, \
    ContentTypeSerializer, GroupSerializer, AdminSerializer, SPUSerializer2, BrandSerializer, \
    SPUGoodsCategorySerializer, SPUSpecSerializer, BrandSerializer2, SPUSpecSerializer2, GoodsChannelSerializer, \
    GroupChannelSerializer
from apps.meiduo_admin.utils import PageNum
from apps.orders.models import OrderInfo
from apps.users.models import User
from apps.goods.models import GoodsVisitCount, SPUSpecification, SPU, SKUImage, SKU, GoodsCategory, Brand, \
    SpecificationOption, GoodsChannel, GoodsChannelGroup

# 注册用户统计
from meiduo_mail import settings


class UserTotalCountView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        now_date = date.today()
        count = User.objects.filter(is_staff=False).count()
        return Response({
            'count': count
        })


# 日增用户统计
class UserDayCountView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        now_date = date.today()
        count = User.objects.filter(date_joined__gte=now_date, is_staff=False).count()
        return Response({
            'count': count
        })


# 日活用户统计
class UserActiveCountView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        now_date = date.today()
        count = User.objects.filter(last_login__gte=now_date, is_staff=False).count()
        return Response({
            'count': count
        })


# 日下单用户统计
class UserOrderCountView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        now_date = date.today()
        users = set(User.objects.filter(orderinfo__create_time__gte=now_date))
        count = len(users)
        return Response({
            'count': count,
        })


# 月增用户统计
class UserMonthCountView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        now_date = date.today()
        start_date = now_date - timedelta(30)
        data_list = []
        for i in range(30):
            index_date = start_date + timedelta(days=i)
            next_date = start_date + timedelta(i + 1)
            count = User.objects.filter(date_joined__gte=index_date, date_joined__lt=next_date).count()
            data_list.append({
                'count': count,
                'date': index_date
            })
        return Response(
            data_list
        )


# 商品访问量统计
class GoodsDayView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        now_date = date.today()
        goods = GoodsVisitCount.objects.filter(date__gte=now_date)
        date_list = []
        for i in goods:
            date_list.append({
                'count': i.count,
                'category': i.category.name
            })
        return Response(date_list)


# 增加用户
class UserView(ListCreateAPIView):
    queryset = User.objects.filter(is_staff=False)
    serializer_class = UserSerializer
    pagination_class = PageNum

    def get_queryset(self):
        keywork = self.request.query_params.get('keyword')
        if keywork is None or keywork == '':
            return User.objects.filter(is_staff=False)
        else:
            return User.objects.filter(is_staff=False, username=keywork)


# 表数据获取
class SpecsView(ModelViewSet):
    queryset = SPUSpecification.objects.all()
    serializer_class = SPUSpecificationSerializer
    pagination_class = PageNum
    permission_classes = [IsAdminUser]

    # 表数据保存
    def simple(self, request):
        spus = SPU.objects.all()
        ser = SPUSerializer(spus, many=True)
        return Response(ser.data)


# 图片表获取
class ImageView(ModelViewSet):
    queryset = SKUImage.objects.all()
    serializer_class = SKUImageSerializer
    pagination_class = PageNum
    permission_classes = [IsAdminUser]

    def simple(self, request):
        skus = SKU.objects.all()
        ser = SKUSerializer(skus, many=True)
        return Response(ser.data)


# 商品SKU
class SKUView(ModelViewSet):
    queryset = SKU.objects.all()
    serializer_class = SKUSerializer
    pagination_class = PageNum
    permission_classes = [IsAdminUser]

    def get_queryset(self):
        keyword = self.request.query_params.get('kew')
        if keyword is None or keyword == '':
            return SKU.objects.all()
        else:
            return SKU.objects.filter(name__contains=keyword)

    @action(methods=['get'], detail=False)
    def categories(self, request):
        data = GoodsCategory.objects.filter(subs=None)
        ser = GoodsCategorySerializer(data, many=True)

        return Response(ser.data)

    def specs(self, request, pk):
        data = SPUSpecification.objects.filter(spu_id=pk)
        ser = SPUSpecificationSerializer2(data, many=True)
        return Response(ser.data)


# 订单
class OrderView(ModelViewSet):
    queryset = OrderInfo.objects.all()
    serializer_class = OrderInfoSerializer
    pagination_class = PageNum
    permission_classes = [IsAdminUser]

    def get_queryset(self):
        keyword = self.request.query_params.get('keyword')
        if keyword is None or keyword == '':
            return OrderInfo.objects.all()
        else:
            return OrderInfo.objects.filter(order_id__contains=keyword)

    @action(methods=['put'], detail=True)
    def status(self, request, pk):
        try:
            order = OrderInfo.objects.get(order_id=pk)
        except:
            return Response({
                'error': '订单不存在'
            }, status=400)
        status = request.data.get('status')
        order.status = status
        order.save()
        return Response({
            'order_id': pk,
            'status': status
        })


# 权限信息
class PermissionView(ModelViewSet):
    queryset = Permission.objects.all()
    serializer_class = PermissionSerializer
    pagination_class = PageNum
    permission_classes = [IsAdminUser]

    def content_types(self, request):
        contentype = ContentType.objects.all()
        ser = ContentTypeSerializer(contentype, many=True)
        return Response(ser.data)


# 分组表
class GroupView(ModelViewSet):
    queryset = Group.objects.all()
    serializer_class = GroupSerializer
    pagination_class = PageNum
    permission_classes = [IsAdminUser]

    def simple(self, request):
        pers = Permission.objects.all()
        ser = PermissionSerializer(pers, many=True)
        return Response(ser.data)


# 管理员
class AdminView(ModelViewSet):
    queryset = User.objects.all()
    serializer_class = AdminSerializer
    pagination_class = PageNum
    permission_classes = [IsAdminUser]

    def simple(self, request):
        groups = Group.objects.all()
        ser = GroupSerializer(groups, many=True)
        return Response(ser.data)


# SPU表
class SPUView(ModelViewSet):
    queryset = SPU.objects.all()
    serializer_class = SPUSerializer2
    pagination_class = PageNum
    permission_classes = [IsAdminUser]

    @action(methods=['get'], detail=False)
    def get_queryset(self):
        keyword = self.request.query_params.get('keyword')
        if keyword is None or keyword == '':
            return SPU.objects.all()
        else:
            return SPU.objects.filter(name__contains=keyword)

    def brand(self, request):
        data = Brand.objects.all()
        ser = BrandSerializer(data, many=True)
        return Response(ser.data)

    def simple(self, request):
        chan = GoodsCategory.objects.all()
        ser = GoodsCategorySerializer(chan, many=True)
        return Response(ser.data)

    def category(self, request, pk):
        data1 = GoodsCategory.objects.filter(parent_id=pk)
        ser = SPUGoodsCategorySerializer(data1, many=True)
        return Response(ser.data)


# 规格管理
class SPUSpecsView(ModelViewSet):
    queryset = SpecificationOption.objects.all()
    serializer_class = SPUSpecSerializer
    pagination_class = PageNum
    permission_classes = [IsAdminUser]

    def simple(self, request):
        spec = SPUSpecification.objects.all()
        ser = SPUSpecSerializer2(spec, many=True)
        return Response(ser.data)


# 品牌管理
class BrandView(ModelViewSet):
    queryset = Brand.objects.all()
    serializer_class = BrandSerializer2
    pagination_class = PageNum
    permission_classes = [IsAdminUser]

    @action(methods=['get'], detail=False)
    def simple(self, request):
        brand = Brand.objects.all()
        ser = BrandSerializer2(brand, many=True)
        return Response(ser.data)

        # def brand(self, request, pk):
        #     data1 = Brand.objects.filter(id=pk)
        #     ser = BrandSerializer2(data1, many=True)
        #     return Response(ser.data)


# 频道管理
class GoodsChannelView(ModelViewSet):
    queryset = GoodsChannel.objects.all()
    serializer_class = GoodsChannelSerializer
    pagination_class = PageNum
    permission_classes = [IsAdminUser]

    def simple(self, request):
        channe = GoodsChannelGroup.objects.all()
        ser = GroupChannelSerializer(channe, many=True)
        return Response(ser.data)

    def type(self, request):
        c_type = GoodsCategory.objects.all()
        ser = SPUGoodsCategorySerializer(c_type, many=True)
        return Response(ser.data)


